//
//  SWIndexViewController.swift
//  ChildStory
//
//  Created by linhan on 16/7/15.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWIndexViewController: SWBaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource,ScrollTabBarDelegate
{
    private var _pageController:UIPageViewController?
    private var _viewControllers:[UIViewController] = []
    private var _segmentControl:ScrollTabBar = ScrollTabBar()
    
    deinit
    {
        NotificationCenter.default.removeObserver(self)
        trace("DEINIT SWIndexViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override func viewWillLayoutFirstTime(){
        //setup()
    }
    
    private func setup()
    {
        view.backgroundColor = UIColor.white
        automaticallyAdjustsScrollViewInsets = false
        
        createNavigationRightCustomButton(nil, image: UIImage(named: "main_img_avatar"), target: self, action: #selector(rightBtnTapped))
        
        _viewControllers.append(SWTodayViewController())
        _viewControllers.append(SWEventsViewController())
        
        _pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        _pageController?.dataSource = self
        _pageController?.delegate = self
        _pageController?.setViewControllers([_viewControllers[0]], direction: .forward, animated: true, completion: nil)
        _pageController?.view?.backgroundColor = UIColor(hex: 0xedeeef)
        _pageController?.view.frame = view.bounds
        addChildViewController(_pageController!)
        view.addSubview(_pageController!.view)
        
        _segmentControl.delegate = self
        _segmentControl.font = UIFont.systemFont(ofSize: 18)
        _segmentControl.itemSpacing = 30
        _segmentControl.selectedColor = UIColor(hex: 0x303332)
        _segmentControl.unselectedColor = UIColor(hex: 0xa5a6a3)
        _segmentControl.titleItems = ["今日","事件"]
        _segmentControl.selectedIndex = 0
        _segmentControl.sizeToFit()
        navigationItem.titleView = _segmentControl
        
        NotificationCenter.default.addObserver(self, selector: #selector(navigationNotification(_:)), name: NotificationName.Navigation, object: nil)
        
        //直到注册成功，进入首页才索取推送通知权限
        SWPushManager.shared().registerRemoteNotification()
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of:viewController) , index > 0 else
        {
            return nil
        }
        return _viewControllers.valueAt(index - 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of:viewController) , index < _viewControllers.count - 1 else
        {
            return nil
        }
        return _viewControllers.valueAt(index + 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
    {
        if let currnetViewController = pageViewController.viewControllers?.last , completed
        {
            let index = _viewControllers.index(of:currnetViewController) ?? 0
            _segmentControl.selectedIndex = index
        }
    }
    
    func scrollTabBar(_ tabBar: ScrollTabBar, didSelectIndex index: Int)
    {
        let direction:UIPageViewControllerNavigationDirection = index == 1 ? .forward : .reverse
        if let viewController = _viewControllers.valueAt(index)
        {
            _pageController?.setViewControllers([viewController], direction: direction, animated: true, completion: nil)
        }
    }
    
    @objc private func navigationNotification(_ notification:Notification)
    {
        if let viewController = notification.userInfo?[SWKey.ViewController] as? String
        {
            if let eventViewController = _viewControllers.last,
                let current = _pageController?.viewControllers?.first,viewController == "SWEventsViewController" && !(current is SWEventsViewController)
            {
                _pageController?.setViewControllers([eventViewController], direction: .forward, animated: false, completion: nil)
                _segmentControl.selectedIndex = 1
            }
        }
    }
    
    @objc private func rightBtnTapped()
    {
        navigationController?.pushViewController(SWProfileViewController(), animated: true)
    }
    
}
